<template>
  <div class="upload-container">
    <el-row :gutter="24">
      <el-col :span="16">
        <el-card class="upload-card">
          <template #header>
            <div class="card-header">
              <h3>文档上传</h3>
            </div>
          </template>
          
          <el-upload
            class="upload-area"
            drag
            action="/api/upload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            name="file"
            multiple>
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持上传PDF、Word、Excel、PPT、CAD等格式文件
              </div>
            </template>
          </el-upload>

          <el-divider>已上传文档</el-divider>

          <el-table :data="documents" style="width: 100%">
            <el-table-column prop="name" label="文件名" min-width="200" />
            <el-table-column prop="type" label="类型" width="120" />
            <el-table-column prop="size" label="大小" width="120" align="right" />
            <el-table-column prop="status" label="状态" width="120" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.status === 'success' ? 'success' : 'warning'">
                  {{ scope.row.status === 'success' ? '处理完成' : '处理中' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center" fixed="right">
              <template #default="scope">
                <el-button
                  size="small"
                  @click="handlePreview(scope.row)">预览</el-button>
                <el-button
                  size="small"
                  type="danger"
                  :loading="deletingFileId === scope.row.id"
                  :disabled="deletingFileId === scope.row.id"
                  @click="handleDelete(scope.row)">
                  {{ deletingFileId === scope.row.id ? '删除中...' : '删除' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="upload-stats">
          <template #header>
            <div class="card-header">
              <h3>上传统计</h3>
            </div>
          </template>
          
          <div class="stats-content">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-statistic title="今日上传" :value="0" />
              </el-col>
              <el-col :span="12">
                <el-statistic title="总文档数" :value="documents.length" />
              </el-col>
            </el-row>
            
            <el-divider>文档类型分布</el-divider>
            
            <div class="type-distribution">
              <div class="type-item" v-for="type in ['PDF', 'Word', 'Excel', 'PPT', 'CAD']" :key="type">
                <span class="type-name">{{ type }}</span>
                <el-progress :percentage="30" :stroke-width="8" />
              </div>
            </div>
          </div>
        </el-card>
        
        <el-card class="upload-guide" style="margin-top: 24px;">
          <template #header>
            <div class="card-header">
              <h3>上传指南</h3>
            </div>
          </template>
          
          <el-timeline>
            <el-timeline-item
              v-for="(guide, index) in uploadGuides"
              :key="index"
              :type="guide.type">
              {{ guide.content }}
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="文档预览"
      width="70%"
      :destroy-on-close="true">
      <div class="preview-content">
        <iframe
          v-if="currentPreviewUrl"
          :src="currentPreviewUrl"
          width="100%"
          height="600px"
          frameborder="0">
        </iframe>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import { useAppStore } from '../stores'
import { ElMessage, ElMessageBox } from 'element-plus'

const store = useAppStore()

// 文档列表
const documents = ref([])

// 上传头信息 - 移除手动设置的 Content-Type，让浏览器自动处理
const uploadHeaders = ref({})

// 预览相关
const previewVisible = ref(false)
const currentPreviewUrl = ref('')

// 删除状态
const deletingFileId = ref(null)

// 上传指南
const uploadGuides = [
  { content: '支持多种文档格式上传', type: 'primary' },
  { content: '单个文件大小不超过50MB', type: 'warning' },
  { content: '上传后自动进行文字识别', type: 'success' },
  { content: '支持批量上传多个文件', type: 'info' }
]

// 获取已上传文件列表
const fetchDocuments = async () => {
  try {
    const response = await fetch('/api/upload');
    const data = await response.json();
    if (data.success) {
      documents.value = data.data.map(file => ({
        id: file.id,
        name: file.originalName,
        type: file.mimetype,
        size: (file.size / 1024).toFixed(2) + 'KB',
        status: 'success',
        url: file.url
      }));
    }
  } catch (error) {
    console.error('获取文件列表失败:', error);
    ElMessage.error('获取文件列表失败');
  }
};

// 组件挂载时获取文件列表
onMounted(() => {
  fetchDocuments();
});

// 上传前验证
const beforeUpload = (file) => {
  const validTypes = ['application/pdf', 'application/msword', 
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/vnd.ms-powerpoint',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'application/x-dxf']
  
  if (!validTypes.includes(file.type)) {
    ElMessage.error('不支持的文件类型！')
    return false
  }
  return true
}

// 上传成功处理
const handleUploadSuccess = async (response, file) => {
  if (response.success) {
    const fileData = response.data;
    const newDoc = {
      id: fileData.id,
      name: fileData.originalName,
      type: fileData.mimetype,
      size: (fileData.size / 1024).toFixed(2) + 'KB',
      status: 'success',
      url: fileData.url
    }
    
    // 添加到本地列表
    documents.value.push(newDoc)
    store.uploadDocument(newDoc)
    ElMessage.success('上传成功')
    
    // 重新获取文件列表，确保数据完全同步
    await fetchDocuments()
  } else {
    ElMessage.error(response.error?.message || '上传失败')
  }
}

// 上传失败处理
const handleUploadError = () => {
  ElMessage.error('上传失败，请重试')
}

// 预览文档
const handlePreview = (row) => {
  currentPreviewUrl.value = row.url
  previewVisible.value = true
}

// 删除文档
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该文档吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 设置删除状态
    deletingFileId.value = row.id
    
    try {
      // 调用后端 API 删除文件
      const response = await fetch(`/api/upload/${encodeURIComponent(row.id)}`, {
        method: 'DELETE'
      })
      
      const result = await response.json()
      
      if (result.success) {
        ElMessage.success('删除成功')
        // 重新获取文件列表，确保数据同步
        await fetchDocuments()
      } else {
        ElMessage.error(result.error?.message || '删除失败')
      }
    } finally {
      // 清除删除状态
      deletingFileId.value = null
    }
  } catch (error) {
    if (error !== 'cancel') { // 用户取消删除时不显示错误
      console.error('删除文件失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}
</script>

<style scoped>
.upload-container {
  background-color: #f5f7fa;
}

.upload-card,
.upload-stats,
.upload-guide {
  margin-bottom: 24px;
}

.upload-area {
  width: 100%;
  margin-bottom: 24px;
}

.preview-content {
  display: flex;
  justify-content: center;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.stats-content {
  padding: 20px 0;
}

.type-distribution {
  margin-top: 20px;
}

.type-item {
  margin-bottom: 15px;
}

.type-name {
  display: inline-block;
  width: 60px;
  margin-right: 10px;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
}

:deep(.el-timeline-item__node--primary) {
  background-color: var(--el-color-primary);
}

:deep(.el-timeline-item__node--success) {
  background-color: var(--el-color-success);
}

:deep(.el-timeline-item__node--warning) {
  background-color: var(--el-color-warning);
}

:deep(.el-timeline-item__node--info) {
  background-color: var(--el-color-info);
}
</style>